package com.example.chenjun.myapplication.net.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.example.chenjun.myapplication.net.BaseLoader;
import com.example.chenjun.myapplication.net.NetController;
import com.example.chenjun.myapplication.net.netcallback.BaseCallback;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OkHttpLoader extends BaseLoader {

    private static final Handler H = new Handler(Looper.getMainLooper());

    public OkHttpLoader(NetController controller) {
        super(controller);
    }

    @Override
    public String enqueue() {
        Call call = OkhttpUtil.newCall(mController);
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void execute(final BaseCallback callback) {
        Call call = OkhttpUtil.newCall(mController);
        OkhttpUtil.newCall(mController);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull final Call call, @NonNull final IOException e) {
                H.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onError(e);
                    }
                });
            }

            @Override
            public void onResponse(@NonNull final Call call, @NonNull final Response response) throws IOException {

                final String content = response.body().string();
                H.post(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            callback.onResponse(callback.parse(content));
                        }catch (NullPointerException e){
                            callback.onResponse(content);
                        }
                    }
                });
            }
        });
    }

    @Override
    public File downFile() {
        return null;
    }
}
